package com.cwx.mychat.controller;

import com.cwx.mychat.entity.dto.TokenUserInfoDto;
import com.cwx.mychat.entity.enums.ExceptionBizCodeEnum;
import com.cwx.mychat.entity.po.ChatMessage;
import com.cwx.mychat.exception.BusinessException;
import com.cwx.mychat.service.ChatMessageService;
import com.cwx.mychat.utils.R;
import com.cwx.mychat.utils.common.CommonUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


/**
 * 作者： cwx
 * 时间： 2024/9/27 13:08
 * 版本： 1.0
 * 注释：
 */
@RestController
@Validated
@RequestMapping("/message")
public class ChatMessageController extends BaseController<ChatMessageService, ChatMessage>{


    @Autowired
    private ChatMessageService chatMessageService;


    /**
     * 发送消息
     * @param chatMessage
     * @return
     */
    @PostMapping("/save")
    public R saveChatMessage(@RequestBody ChatMessage chatMessage) throws BusinessException {
        //获取当前线程的用户
        TokenUserInfoDto tokenUserInfoDto = CommonUtil.getSecurityContext();
        R r = chatMessageService.sendMessage(chatMessage, tokenUserInfoDto);
        if(r == null){
            return R.error(ExceptionBizCodeEnum.NOT_FOUND_ACCOUNT.getMsg());
        }
        return r;
    }

    /**
     * 上传文件
     * @param file
     * @param messageId
     * @return
     * @throws BusinessException
     */
    @PostMapping("/uploadFile")
    public R uploadFile(@NotNull MultipartFile file, @NotNull Long messageId) throws BusinessException {
        //获取当前线程
        TokenUserInfoDto tokenUserInfoDto = CommonUtil.getSecurityContext();
        return chatMessageService.sendFile(file, tokenUserInfoDto, messageId);

    }

    /**
     * 下载文件
     * @param messageId
     * @return
     */
    @GetMapping("/downloadFile")
    public R downloadFile(@NotNull Long messageId, HttpServletResponse response){
        //获取当前线程
        TokenUserInfoDto tokenUserInfoDto = CommonUtil.getSecurityContext();
        return chatMessageService.saveMessageFile(tokenUserInfoDto, messageId, response);
    }
}
